import axios from 'axios'
import { getToken, history } from '@/utils'

const http = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0',
  timeout: 5000,
})

// 拦截器
http.interceptors.request.use(
  (config) => {
    if (getToken()) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应
http.interceptors.response.use(
  (res) => {
    return res.data
  },
  (err) => {
    if (err.response.status === 401) {
      history.push('/login')
    }
    return err.response
  }
)

export default http
